﻿using Coldairarrow.Business.Base_Manage;
using Coldairarrow.Entity.Base_leasesystem_car;
using Coldairarrow.Entity.Base_leasesystem_employee;
using Coldairarrow.Entity.Base_leasesystem_employeesign;
using Coldairarrow.Entity.Base_Leasesystem_equipment;
using Coldairarrow.Entity.Base_leasesystem_service;
using Coldairarrow.Entity.Base_leasesystem_servicesign;
using Coldairarrow.Entity.Base_leasesystem_signfile;
using Coldairarrow.Entity.Base_leasesystem_transactionbatchsub;
using Coldairarrow.Entity.Base_Manage;
using Coldairarrow.Util;
using EFCore.Sharding;
using LinqKit;
using Microsoft.EntityFrameworkCore;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Linq.Dynamic.Core;
using System.Threading.Tasks;

namespace Coldairarrow.Business.Base_leasesystem_employee
{
    public class leasesystem_employeeBusiness : BaseBusiness<leasesystem_employee>, Ileasesystem_employeeBusiness, ITransientDependency
    {
        public leasesystem_employeeBusiness(IDbAccessor db, IHomeBusiness homeBus)
            : base(db)
        {
            _homeBus = homeBus;
        }
        readonly IHomeBusiness _homeBus;
        #region 外部接口

        public async Task<PageResult<leasesystem_employee>> GetDataListAsync(PageInput<ConditionDTO> input)
        {
            var q = GetIQueryable();
            var where = LinqHelper.True<leasesystem_employee>();
            var search = input.Search;

            //筛选
            if (!search.Condition.IsNullOrEmpty() && !search.Keyword.IsNullOrEmpty())
            {
                var newWhere = DynamicExpressionParser.ParseLambda<leasesystem_employee, bool>(
                    ParsingConfig.Default, false, $@"{search.Condition}.Contains(@0)", search.Keyword);
                where = where.And(newWhere);
            }

            return await q.Where(where).GetPageResultAsync(input);
        }

        public async Task<leasesystem_employee> GetTheDataAsync(string id)
        {
            return await GetEntityAsync(id);
        }

        public async Task AddDataAsync(leasesystem_employee data,string id)
        {
            string brandid = Db.GetIQueryable<Base_User>().Where(a => a.Id == id).FirstOrDefault().brandId;
            data.MID = brandid;
            await InsertAsync(data);
        }

        public async Task UpdateDataAsync(leasesystem_employee data)
        {
            await UpdateAsync(data);
        }


        public async Task DeleteDataAsync(List<string> ids)
        {
            for (int i = 0; i < ids.Count; i++)
            {
                
                //代发明细
                var batchsub = Db.GetIQueryable<leasesystem_transactionbatchsub>().Where(a => a.employeeId == ids[i] && a.trxSts =="1");
                if (batchsub.Count() < 1)
                {
                    //出租人持有得车辆和设备信息
                    var carinfo =await  Db.GetIQueryable<leasesystem_car>().Where(a => a.EmpId == ids[i]).ToListAsync();
                    var device =await Db.GetIQueryable<leasesystem_equipment>().Where(a => a.EmpId == ids[i]).ToListAsync();
                    carinfo.ForEach(a=> {
                        if (!a.VehiclelicensePhoto.IsNullOrEmpty()) {
                            string VehiclelicensePhoto = a.VehiclelicensePhoto.Split('/')[4];
                            _homeBus.DeleteFile(Directory.GetCurrentDirectory() + $"\\wwwroot\\Upload\\{VehiclelicensePhoto}");
                        }
                        if (!a.BuyCarInvoicePhoto.IsNullOrEmpty()) {
                            string BuyCarInvoicePhoto = a.BuyCarInvoicePhoto.Split('/')[4];
                            _homeBus.DeleteFile(Directory.GetCurrentDirectory() + $"\\wwwroot\\Upload\\{BuyCarInvoicePhoto}");
                        }
                        if (!a.CompulsoryinsurancePhoto.IsNullOrEmpty())
                        {
                            string CompulsoryinsurancePhoto = a.CompulsoryinsurancePhoto.Split('/')[4];
                            _homeBus.DeleteFile(Directory.GetCurrentDirectory() + $"\\wwwroot\\Upload\\{CompulsoryinsurancePhoto}");
                        }
                        if (!a.CommercialinsurancePhoto.IsNullOrEmpty())
                        {
                            string CommercialinsurancePhoto = a.CommercialinsurancePhoto.Split('/')[4];
                            _homeBus.DeleteFile(Directory.GetCurrentDirectory() + $"\\wwwroot\\Upload\\{CommercialinsurancePhoto}");
                        }
                        if (!a.CarfrontPhoto.IsNullOrEmpty())
                        {
                            string CarfrontPhoto = a.CarfrontPhoto.Split('/')[4];
                            _homeBus.DeleteFile(Directory.GetCurrentDirectory() + $"\\wwwroot\\Upload\\{CarfrontPhoto}");
                        }
                        if (!a.CarbackPhoto.IsNullOrEmpty())
                        {
                            string CarbackPhoto = a.CarbackPhoto.Split('/')[4];
                            _homeBus.DeleteFile(Directory.GetCurrentDirectory() + $"\\wwwroot\\Upload\\{CarbackPhoto}");
                        }
                    });

                    device.ForEach(a =>
                    {
                        if (!a.VehiclelicensePhoto.IsNullOrEmpty())
                        {
                            string VehiclelicensePhoto = a.VehiclelicensePhoto.Split('/')[4];
                            _homeBus.DeleteFile(Directory.GetCurrentDirectory() + $"\\wwwroot\\Upload\\{VehiclelicensePhoto}");
                        }
                        if (!a.BuyDeviceInvoicePhoto.IsNullOrEmpty())
                        {
                            string BuyDeviceInvoicePhoto = a.BuyDeviceInvoicePhoto.Split('/')[4];
                            _homeBus.DeleteFile(Directory.GetCurrentDirectory() + $"\\wwwroot\\Upload\\{BuyDeviceInvoicePhoto}");
                        }
                        if (!a.CompulsoryinsurancePhoto.IsNullOrEmpty())
                        {
                            string CompulsoryinsurancePhoto = a.CompulsoryinsurancePhoto.Split('/')[4];
                            _homeBus.DeleteFile(Directory.GetCurrentDirectory() + $"\\wwwroot\\Upload\\{CompulsoryinsurancePhoto}");
                        }
                        if (!a.CommercialinsurancePhoto.IsNullOrEmpty())
                        {
                            string CommercialinsurancePhoto = a.CommercialinsurancePhoto.Split('/')[4];
                            _homeBus.DeleteFile(Directory.GetCurrentDirectory() + $"\\wwwroot\\Upload\\{CommercialinsurancePhoto}");
                        }
                        if (!a.DevicefrontPhoto.IsNullOrEmpty())
                        {
                            string DevicefrontPhoto = a.DevicefrontPhoto.Split('/')[4];
                            _homeBus.DeleteFile(Directory.GetCurrentDirectory() + $"\\wwwroot\\Upload\\{DevicefrontPhoto}");
                        }
                        if (!a.DevicesidePhoto.IsNullOrEmpty())
                        {
                            string DevicesidePhoto = a.DevicesidePhoto.Split('/')[4];
                            _homeBus.DeleteFile(Directory.GetCurrentDirectory() + $"\\wwwroot\\Upload\\{DevicesidePhoto}");
                        }
                        if (!a.DeviceNameplate.IsNullOrEmpty())
                        {
                            string DeviceNameplate = a.DeviceNameplate.Split('/')[4];
                            _homeBus.DeleteFile(Directory.GetCurrentDirectory() + $"\\wwwroot\\Upload\\{DeviceNameplate}");
                        }
                        if (!a.DeviceCertification.IsNullOrEmpty())
                        {
                            string DeviceCertification = a.DeviceCertification.Split('/')[4];
                            _homeBus.DeleteFile(Directory.GetCurrentDirectory() + $"\\wwwroot\\Upload\\{DeviceCertification}");
                        }
                    });
                    //出租人签约，签约附件
                    var empsign = await Db.GetIQueryable<leasesystem_employeesign>().Where(a => a.employeeId == ids[i]).ToListAsync();
                    if (empsign.Count>=1) {
                        empsign.ForEach(a => {
                            var empsignfile = Db.GetIQueryable<leasesystem_signfile>().Where(b => a.SignFiled == b.Id);
                            if (empsignfile.Count() >= 1)
                            {
                                empsignfile.ForEach(a=> {
                                    if (!a.ContractdownUrl.IsNullOrEmpty()) {
                                        string ContractdownUrl = a.ContractdownUrl.Split('/')[4];
                                        _homeBus.DeleteFile(Directory.GetCurrentDirectory() + $"\\wwwroot\\Upload\\{ContractdownUrl}");
                                    }
                                });
                                Db.DeleteAsync(empsignfile);
                            }
                        });
                    }

                    if (carinfo.Count()>=1) {

                        await Db.DeleteAsync(carinfo);
                    }
                    if (device.Count() >= 1)
                    {
                        await Db.DeleteAsync(device);
                    }
                    await DeleteAsync(ids[i]);
                }
                else {
                    throw new BusException("该出租人已收租金无法删除!");
                }
                
            }
            
        }

        public async Task AuthenEmp(List<string> EID,string userid)
        {
            for (int i = 0; i < EID.Count; i++)
            {

                //出租人数据
                var EmpEntity = Db.GetEntity<leasesystem_employee>(EID[i]);
                EmpEntity.AuditInf = 1;
                //客户签约
                var MSign = Db.GetIQueryable<leasesystem_servicesign>().Where(a => a.MID == EmpEntity.MID).FirstOrDefault();

                var empsign = await Db.GetIQueryable<leasesystem_employeesign>().Where(a => a.employeeId == EID[i] && a.ServiceID == MSign.ServiceId).FirstOrDefaultAsync();
                if (empsign == null) {
                    leasesystem_employeesign sign = new leasesystem_employeesign();
                    sign.Id = IdHelper.GetId();
                    sign.ServiceID = MSign.ServiceId;

                    sign.ServiceName = Db.GetEntity<leasesystem_service>(sign.ServiceID).ServiceName;
                    sign.BeginDate = DateTime.Now.ToString("yyyy-MM-dd");
                    string date = (DateTime.Now.Year + 1).ToString() + "-" + DateTime.Now.Month + "-" + DateTime.Now.Day;
                    sign.EndDate = date;
                    sign.zt = 0;
                    sign.CreateTime = DateTime.Now;
                    sign.CreatorId = userid;
                    sign.employeeId = EID[i];
                    sign.SignFiled = IdHelper.GetId();
                    await Db.InsertAsync(sign);
                }

                await Db.UpdateAsync(EmpEntity);
            }
        }

        public object GetHeightSearch(PageInput<ConditionDTO> input)
        {
            var q = Db.GetIQueryable<leasesystem_employee>();
            var newWhere = q;


            if (!input.Search.Keyword.IsNullOrEmpty())
            {
                newWhere = newWhere.Where(a => a.EmpName.Contains(input.Search.Keyword));
            }
            if (!input.Search.IdNumber.IsNullOrEmpty())
            {
                newWhere = newWhere.Where(a => a.IdCardNo.Contains(input.Search.IdNumber));
            }

            if (!input.Search.BankCardNo.IsNullOrEmpty())
            {
                newWhere = newWhere.Where(a => a.BankCardNo.Contains(input.Search.BankCardNo));
            }
            if (!input.Search.EmpPhone.IsNullOrEmpty())
            {
                newWhere = newWhere.Where(a => a.EmpPhone.Contains(input.Search.EmpPhone));
            }
            if (!input.Search.AuditInf.IsNullOrEmpty())
            {
                newWhere = newWhere.Where(a => a.AuditInf.ToString() == input.Search.AuditInf);
            }
           
            var Data = new
            {
                Data = newWhere.Skip((input.PageIndex - 1) * input.PageRows)
               .Take(input.PageRows),
                Total = q.Count()
            };
            return Data;

        }

        public async Task<object> GetEmpCar(string id)
        {
            var res = await  Db.GetIQueryable<leasesystem_employee>().Where(a => a.Id == id).Join(
                Db.GetIQueryable<leasesystem_car>(), a => a.Id, b => b.EmpId, (a, b) => new
                {
                    b.Id,
                    b.CarNo,
                    b.CarBrandModel,
                    b.Status,
                    b.CreateTime
                }).ToListAsync();
            return res;
        }
        #endregion

        #region 私有成员

        #endregion
    }
}